﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CommonHelper
{
    public class winAPI
    {

        [DllImport("user32.dll", EntryPoint = "GetForegroundWindow")]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern IntPtr SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        public extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        /// 獲得子窗口句柄
        /// </summary>
        /// <param name="parent">上級窗口句柄</param>
        /// <param name="child">傳入同級窗口句柄查找同級的窗口句柄或傳入IntPtr.Zero找查下級窗口句柄</param>
        /// <param name="classname">類名</param>
        /// <param name="captionName">文本名</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "FindWindowEx", CharSet = CharSet.Auto)]
        public extern static IntPtr FindWindowEx(IntPtr parent, IntPtr child, string classname, string captionName);

        /// <summary>
        /// 發送消息
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <param name="Msg">模式</param>
        /// <param name="wParam">字符串大小</param>
        /// <param name="lParam">要發送的字符串</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, StringBuilder lParam);

        [DllImport("user32.dll", EntryPoint = "GetWindowText", CharSet = CharSet.Auto)]
        public static extern IntPtr GetWindowText(IntPtr hwnd, StringBuilder lpString, int cch);

        public const int WM_SETTEXT = 0x0C;    //發送字符串
        public const int WM_GETTEXT = 0x0d;     //獲得字符串
        public const int WM_CHAR = 0x0102;    //發送字符串
        public const int WM_GETTEXTLENGTH = 0x0E;  //得到有关文本的长度(不包含空字符)

        public static IntPtr FindWindowByIndex(IntPtr hwndParent, int index)
        {
            if (index == 0)
                return hwndParent;
            else
            {
                int ct = 0;
                IntPtr result = IntPtr.Zero;
                do
                {
                    result = FindWindowEx(hwndParent, result, null, null);
                    if (result != IntPtr.Zero)
                        ++ct;
                } while (ct < index && result != IntPtr.Zero);
                return result;
            }
        }


    }
}
